﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Net.Mail;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
using System.Text;

namespace MII_FIF.Layouts.MII_FIF.DataKunjungan
{
    public partial class FormDataKunjungan : LayoutsPageBase
    {
        SqlConnection conn;
        DataTable dt;
        SqlDataAdapter adapt;
        //string connStr = "Data Source=sp2013-server;Initial Catalog=InventoryManagement;User ID=sa;Password=P@ssw0rd";
        string queryStr = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.DataKunjunganGroupName))
            {
                btnCancel.Click += btnCancel_Click;
                btnSubmit.Click += btnSubmit_Click;
                btnDelete.Click += btnDelete_Click;
                btnAdd.Click += btnAdd_Click;
                GridTrouble.RowEditing += GridTrouble_RowEditing;
                GridTrouble.RowUpdating += GridTrouble_RowUpdating;
                GridTrouble.RowCancelingEdit += GridTrouble_RowCancelingEdit;

                btnDelete2.Click += btnDelete2_Click;
                GridPrinter.RowEditing += GridPrinter_RowEditing;
                GridPrinter.RowUpdating += GridPrinter_RowUpdating;
                GridPrinter.RowCancelingEdit += GridPrinter_RowCancelingEdit;

                if (!IsPostBack)
                {
                    btnDelete2.Visible = false;
                    Initialize();
                    if (Request.QueryString["ID"] != null)
                        ViewState["ID"] = Request.QueryString["ID"].ToString();

                    ((Label)Header.FindControl("lblHeader")).Text = "Form Kunjungan Rutin Cabang/Pos FIF";
                    LoadDatacabang();
                }

                if (checkKunjungan.SelectedValue.ToString() == "1")
                    grpKunjungan.Visible = true;
                else
                    grpKunjungan.Visible = false;

                if (checkTrouble.SelectedValue.ToString() == "2")
                    grpTrouble.Visible = true;
                else
                    grpTrouble.Visible = false;

                if (checkDeployment.SelectedValue.ToString() == "3")
                    grpDeployment.Visible = true;
                else
                    grpDeployment.Visible = false;

                if (checkLain.SelectedValue.ToString() == "4")
                    grpLain.Visible = true;
                else
                    grpLain.Visible = false;
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }

        void Initialize()
        {
            //lblEngineer.Text = Generic.GetUserLoginReformat();
            lblLogin.Text = SPContext.Current.Web.CurrentUser.Name;

            if (Request.QueryString["ID"] != null)
            {

            }
            else
            {
                DataTable DTTrouble = new DataTable();
                DTTrouble.Columns.Add(new DataColumn("JenisTrouble", typeof(string)));
                DTTrouble.Columns.Add(new DataColumn("Solusi", typeof(string)));
                DTTrouble.Columns.Add(new DataColumn("ID", typeof(string)));
                ViewState["DTTrouble"] = DTTrouble;

                DataTable DTPrinter = new DataTable();
                DTPrinter.Columns.Add(new DataColumn("NamaPrinter", typeof(string)));
                DTPrinter.Columns.Add(new DataColumn("JmlPrinter", typeof(string)));
                DTPrinter.Columns.Add(new DataColumn("ID", typeof(string)));
                ViewState["DTPrinter"] = DTPrinter;
            }
        }

        protected DataTable ExecuteDataTable(string queryStr)
        {
            //conn = new SqlConnection(connStr);
            conn = new SqlConnection(Configuration.DBConnection());
            conn.Open();
            adapt = new SqlDataAdapter(queryStr, conn);
            dt = new DataTable();
            adapt.Fill(dt);
            conn.Dispose();
            return dt;
        }

        #region Trouble
        void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtJenisTrouble.Text.ToString() != "" && txtSolusi.Text.ToString() != "")
            {
                DataTable DTTrouble = (DataTable)ViewState["DTTrouble"];
                DataRow row = DTTrouble.NewRow();
                row["JenisTrouble"] = txtJenisTrouble.Text;
                row["Solusi"] = txtSolusi.Text;
                row["ID"] = txtJenisTrouble.Text;
                DTTrouble.Rows.Add(row);
                ViewState["DTTrouble"] = DTTrouble;

                GridTrouble.DataSource = ViewState["DTTrouble"];
                GridTrouble.DataBind();

                lblErrorTrouble.Text = "";
            }
            else
                lblErrorTrouble.Text = "Trouble & Solusi Harus Diisi";
            
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            bool delete = false;
            DataTable DTTrouble = ((DataTable)ViewState["DTTrouble"]);
            foreach (GridViewRow row in GridTrouble.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk1");
                if (chk != null)
                    if (chk.Checked)
                    {
                        delete = true;
                        break;
                    }
            }
            if (delete)
            {
                for (int i = GridTrouble.Rows.Count - 1; i > -1; i--)
                {
                    CheckBox chk = (CheckBox)GridTrouble.Rows[i].FindControl("chk1");
                    if (chk != null)
                        if (chk.Checked)
                        {
                            DTTrouble.Rows.RemoveAt(i);
                        }
                }
                GridTrouble.DataSource = DTTrouble;
                GridTrouble.DataBind();
                ViewState["DTTrouble"] = DTTrouble;
            }
        }

        void GridTrouble_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
        {
            GridTrouble.EditIndex = -1;
            GridTrouble.DataSource = ((DataTable)ViewState["DTTrouble"]);
            GridTrouble.DataBind();
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        void GridTrouble_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
        {
            DataTable dt = ((DataTable)ViewState["DTTrouble"]);

            dt.Rows[e.RowIndex]["JenisTrouble"] = ((TextBox)GridTrouble.Rows[e.RowIndex].FindControl("txtJenisTrouble")).Text;
            dt.Rows[e.RowIndex]["Solusi"] = ((TextBox)GridTrouble.Rows[e.RowIndex].FindControl("txtSolusi")).Text;
            dt.Rows[e.RowIndex]["ID"] = ((TextBox)GridTrouble.Rows[e.RowIndex].FindControl("txtJenisTrouble")).Text;

            GridTrouble.EditIndex = -1;
            GridTrouble.DataSource = dt;
            GridTrouble.DataBind();
            ViewState["DTTrouble"] = dt;
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        void GridTrouble_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
        {
            string JenisTrouble = ((Label)GridTrouble.Rows[e.NewEditIndex].FindControl("lblJenisTrouble")).Text.ToString();
            string Solusi = ((Label)GridTrouble.Rows[e.NewEditIndex].FindControl("lblSolusi")).Text.ToString();
            string ID = GridTrouble.Rows[e.NewEditIndex].Cells[3].Text.ToString();

            GridTrouble.EditIndex = e.NewEditIndex;
            GridTrouble.DataSource = ((DataTable)ViewState["DTTrouble"]);
            GridTrouble.DataBind();

            btnAdd.Enabled = false;
            btnDelete.Enabled = false;
            btnCancel.Enabled = false;
            btnSubmit.Enabled = false;
        }
        #endregion

        #region Printer

        void btnDelete2_Click(object sender, EventArgs e)
        {
            bool delete = false;
            DataTable DTPrinter = ((DataTable)ViewState["DTPrinter"]);
            foreach (GridViewRow row in GridPrinter.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk2");
                if (chk != null)
                    if (chk.Checked)
                    {
                        delete = true;
                        break;
                    }
            }
            if (delete)
            {
                for (int i = GridPrinter.Rows.Count - 1; i > -1; i--)
                {
                    CheckBox chk = (CheckBox)GridPrinter.Rows[i].FindControl("chk2");
                    if (chk != null)
                        if (chk.Checked)
                        {
                            DTPrinter.Rows.RemoveAt(i);
                        }
                }
                GridPrinter.DataSource = DTPrinter;
                GridPrinter.DataBind();
                ViewState["DTPrinter"] = DTPrinter;
            }
            if (GridPrinter.Rows.Count < 1)
                btnDelete2.Visible = false;
        }

        void GridPrinter_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
        {
            GridPrinter.EditIndex = -1;
            GridPrinter.DataSource = ((DataTable)ViewState["DTPrinter"]);
            GridPrinter.DataBind();
            //btnAdd.Enabled = true;
            btnDelete2.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        void GridPrinter_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
        {
            DataTable dt = ((DataTable)ViewState["DTPrinter"]);

            //dt.Rows[e.RowIndex]["NamaPrinter"] = ((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtNamaPrinter")).Text;
            dt.Rows[e.RowIndex]["JmlPrinter"] = ((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtJmlPrinter")).Text;
            //dt.Rows[e.RowIndex]["ID"] = ((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtNamaPrinter")).Text;

            GridPrinter.EditIndex = -1;
            GridPrinter.DataSource = dt;
            GridPrinter.DataBind();
            ViewState["DTPrinter"] = dt;
            //btnAdd.Enabled = true;
            btnDelete2.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        void GridPrinter_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
        {
            string NamaPrinter = ((Label)GridPrinter.Rows[e.NewEditIndex].FindControl("lblNamaPrinter")).Text.ToString();
            string JenisPrinter = ((Label)GridPrinter.Rows[e.NewEditIndex].FindControl("lblJmlPrinter")).Text.ToString();
            string ID = GridPrinter.Rows[e.NewEditIndex].Cells[3].Text.ToString();

            GridPrinter.EditIndex = e.NewEditIndex;
            GridPrinter.DataSource = ((DataTable)ViewState["DTPrinter"]);
            GridPrinter.DataBind();

            //btnAdd.Enabled = false;
            btnDelete2.Enabled = false;
            btnCancel.Enabled = false;
            btnSubmit.Enabled = false;
        }

        #endregion

        protected void checkKunjungan_SelectedIndexChanged(object sender, EventArgs e)
        {
            //lblError.Text = CheckBoxList1.SelectedValue.ToString();

            if (checkKunjungan.SelectedValue.ToString() == "1")
                grpKunjungan.Visible = true;
            else
                grpKunjungan.Visible = false;
        }

        protected void checkTrouble_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Label1.Text = CheckBoxList2.SelectedValue.ToString();

            if (checkTrouble.SelectedValue.ToString() == "2")
                grpTrouble.Visible = true;
            else
                grpTrouble.Visible = false;
        }

        protected void checkDeployment_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Label2.Text = CheckBoxList3.SelectedValue.ToString();

            if (checkDeployment.SelectedValue.ToString() == "3")
                grpDeployment.Visible = true;
            else
                grpDeployment.Visible = false;
        }

        protected void checkLain_SelectedIndexChanged(object sender, EventArgs e)
        {

            //Label3.Text = CheckBoxList4.SelectedValue.ToString();

            if (checkLain.SelectedValue.ToString() == "4")
                grpLain.Visible = true;
            else
                grpLain.Visible = false;
        }

        void LoadDatacabang()
        {
            queryStr = @"EXEC Sp_SelectDatacabang";

            dt = ExecuteDataTable(queryStr);
            //bool isExists = false;
            ddlLokasi.Items.Clear();
            ddlLokasi.Items.Add("- SELECT -");

            if (dt.Rows.Count > 0)
            {
                int i = 0;

                for (i = 0; i < dt.Rows.Count; i++)
                {
                    ddlLokasi.Items.Add(new ListItem(dt.Rows[i]["Cabang"].ToString(),dt.Rows[i]["ID"].ToString()));
                }
            }


        }

        void LoadPrinter(String IDCabang)
        {
            try
            {

                queryStr = @"SP_SelectDataPrinterperlabelID '" + IDCabang + "'";

                dt = ExecuteDataTable(queryStr);

                //GridPrinter.DataSource = dt;
                //GridPrinter.DataBind();

                ViewState["DTPrinter"] = dt;
                GridPrinter.DataSource = ViewState["DTPrinter"];
                GridPrinter.DataBind();

                if (dt.Rows.Count != 0)
                    btnDelete2.Visible = true;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDatalabel(String cabang)
        {
            queryStr = @"EXEC SP_SelectDataCabangLabel '" + cabang + "'";
            dt = ExecuteDataTable(queryStr);
            int i = 0;
                lblTelepon.Text = dt.Rows[i]["Telp"].ToString();
                lblPICCabang.Text = dt.Rows[i]["PIC"].ToString();
                lblTlpPIC.Text = dt.Rows[i]["HP"].ToString();
                lblID.Text = dt.Rows[i]["ID"].ToString();

                txtDesktop.Text = dt.Rows[i]["Desktop"].ToString();
                txtNotebook.Text = dt.Rows[i]["Notebook"].ToString();
                txtThinClient.Text = dt.Rows[i]["ThinClient"].ToString();

                LoadPrinter(cabang);
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/DataKunjungan/ViewDataKunjungan.aspx"));
        }

        public void KirimEmail(string namagrup, string namacabang)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = new SPSite(SPContext.Current.Web.Url);
                    SPWeb web = site.OpenWeb();
                    string to = "";
                                      
                    foreach (SPGroup group in web.Groups)
                    {
                        if (group.Name == namagrup)
                        {
                            foreach (SPUser user in group.Users)
                            {
                                if (user.Email != "") to += user.Email + ",";
                            }
                        }
                    }
                    to = to.Substring(0, to.Length - 1);

                    #region sendemail
                    #region headerEmail
                    StringDictionary headers = new StringDictionary();
                    headers.Add("to", to);
                    headers.Add("cc", "");
                    headers.Add("bcc", "");
                    headers.Add("from", "no-reply@fif.co.id");
                    headers.Add("subject", "Approval Data Kunjungan");
                    headers.Add("content-type", "text/html");
                    #endregion
                    #region bodyEmail
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<p>Dear All,</p>" +
                                "<p>Please Review Data Kunjungan " + namacabang + " </p>" +
                                "<p style='font-size:10pt;font-style:italic;color:gray'>This email is generated by system. There's no need to reply.</p>");
                    #endregion
                    SPUtility.SendEmail(SPContext.Current.Web, headers, sb.ToString());
                    #endregion

                });
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                String PICHO = SPContext.Current.Web.CurrentUser.Name;
                String Tanggal = txtDate.Text.ToString();
                String IDCabang = lblID.Text.ToString();
                String KunjunganRutin = checkKunjungan.SelectedValue.ToString();
                String TroubleCabang = checkTrouble.SelectedValue.ToString();
                String DeploymentUnit = checkDeployment.SelectedValue.ToString();
                String Lain2 = checkLain.SelectedValue.ToString();
                String DeskripsiKunjungan = txtDesKunjungan.Text.ToString();
                String DeskripsiLain2 = txtDesLain.Text.ToString();

                if (Tanggal != "" && IDCabang != "")
                {
                    if (KunjunganRutin != "" || TroubleCabang != "" || DeploymentUnit != "" || Lain2 != "")
                    {
                        queryStr = @"EXEC SP_InsertDataKunjungan '" + IDCabang + "','" + KunjunganRutin + "','" + TroubleCabang + "','" + DeploymentUnit + "','" + Lain2 + "','" + DeskripsiKunjungan + "','" + DeskripsiLain2 + "','" + PICHO + "','" + Tanggal + "'";

                        ExecuteDataTable(queryStr);

                        String IDKunjungan = dt.Rows[0]["ID"].ToString();
                        String NamaCabang = dt.Rows[0]["Cabang"].ToString();

                        if (TroubleCabang != "")
                        {
                            using (DataTable dtTrouble = ViewState["DTTrouble"] as DataTable)
                            {
                                foreach (DataRow row in dtTrouble.Rows)
                                {
                                    queryStr = @"SP_InsertDataTroubleCabang '" + row["JenisTrouble"].ToString() + "', '" + row["Solusi"].ToString() + "', '" + IDKunjungan + "'";
                                    ExecuteDataTable(queryStr);
                                }

                            }
                        }

                        if (DeploymentUnit != "")
                        {
                            try
                            {
                                //lblError.Text = "Deployment Unit";

                                String Desktop = txtDesktop.Text.ToString();
                                String Notebook = txtNotebook.Text.ToString();
                                String Thinclient = txtThinClient.Text.ToString();
                                //String Printer = txtPrinter.Text.ToString();

                                queryStr = @"EXEC SP_InsertDataDeploymentUnit '" + Desktop + "','" + Notebook + "','" + Thinclient + "','" + IDKunjungan + "'";
                                ExecuteDataTable(queryStr);

                                //queryStr = @"EXEC SP_DeleteDataDeploymentPrinter '" + IDKunjungan + "'";
                                //ExecuteDataTable(queryStr);

                                using (DataTable dtPrinter = ViewState["DTPrinter"] as DataTable)
                                {
                                    foreach (DataRow row in dtPrinter.Rows)
                                    {
                                        queryStr = @"SP_InsertDataDeploymentPrinter '" + row["ID"].ToString() + "', '" + row["JmlPrinter"].ToString() + "', '" + IDKunjungan + "'";
                                        ExecuteDataTable(queryStr);
                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                lblError.Text = ex.Message.ToString();
                            }

                        }

                        #region Approval

                        //submit data to table approval
                        queryStr = @"SP_InsertDataApproval '" + IDKunjungan
                            + "', 'Data Kunjungan', '" + Generic.GenLink("/_layouts/MII_FIF/FormApproval/Approval_DataKunjungan.aspx?ID=" + IDKunjungan + "") +"', '" + Generic.GetUserLoginReformat() + "'";
                        ExecuteDataTable(queryStr);

                        #endregion

                        //KirimEmail("Approver", NamaCabang);

                        RedirectPageView("Submitted");
                        //Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/DataKunjungan/ViewDataKunjungan.aspx"));
                    }
                    else
                        lblError.Text = "Jenis Kunjungan Harus diisi";
                }
                else
                    lblError.Text = "Tanggal & Lokasi Harus diisi";
          
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message.ToString();
            }
        }

        void RedirectPageView(String status)
        {
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/DataKunjungan/ViewDataKunjungan.aspx?Status=" + status + ""));
        }

        protected void ddlLokasi_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblID.Text = ddlLokasi.SelectedValue.ToString();
            LoadDatalabel(ddlLokasi.SelectedValue.ToString());
        }
    }
}
